package org.pms.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 编写过滤器 - 实现对外公开 api 目录下所有的资源，允许跨域访问
 * @Author zqx
 * @Date 2024-01-02
 */
@WebFilter("/api/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException {
        System.out.println("CoresFilter.....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {

        // 1.向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 2.跨域处理
        // 允许所有的域名
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 允许请求所有的方法
        response.setHeader("Access-Control-Allow-Methods", "*");

        // 允许请求头信息字段（Authorization）
        response.setHeader("Access-Control-Allow-Headers",
                "Authorization,Origin,X-Requested-With,Content-Type,Accept," +
                        "content-Type,origin,x-requested-with,content-type,accept," +
                        "authorization,token,id,X-Custom-Header,X-Cookie," +
                        "Connection,User-Agent,Cookie,*");

        // 3.放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
